package com.hbnu.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author kittychen
 * @since 2025-10-30 19:25
 */
public class UdpReceiveDemo01 {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
            // 1、创建socket
            datagramSocket = new DatagramSocket(8888);   // 监听8888端口

            // 2、定义容器，用于接收发送端发送过来的数据
            byte[] data = new byte[1024];

            // 3、创建数据包，用于封装数据
            DatagramPacket datagramPacket = new DatagramPacket(data, data.length);

            // 4、通过socket接收数据包
            datagramSocket.receive(datagramPacket);  // receive()方法会阻塞，直到有数据发送

            // 从数据报包中解析数据
            String ip = datagramPacket.getAddress().getHostAddress();
            int port = datagramPacket.getPort();
            String content = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
            System.out.println(ip + ":" + port + ":" + content);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 5、关闭资源
            if (datagramSocket != null) {
                datagramSocket.close();
            }
        }
    }
}
